// src/components/core/Pay.tsx
import { Button } from 'antd'
import axios from 'axios'
import React, { FC } from 'react'
import { Link } from 'react-router-dom'
import { API } from '../../config'
import { isAuth } from '../../helpers/auth'
import { CartItem } from '../../helpers/cart'
import { Jwt } from '../../store/models/auth'

interface Props {
    totalPrice: number,
    address: string,
    cart:CartItem[]
}

const Pay: FC<Props> = ({totalPrice, address, cart}) => {
    const getPayUrl = () => {
        axios.post(`${API}/alipay`, {
            totalAmount: totalPrice,
            subject: '测试订单标题',
            body: '测试订单描述',
            products: cart.map(product => ({
                count: product.count,
                product: product._id
            })),
            address,
            useId: (isAuth() as Jwt).user._id
        }).then(response => {
            window.location.href = response.data.result
        })
    }
    const showButton = () => {
        return isAuth() 
            // 已登录显示提交订单按钮
            ? <Button onClick={getPayUrl}>提交订单</Button> 
            // 未登录显示登录按钮
            : (
                <Button>
                    <Link to="/signin">登录</Link>
                </Button>
            )
    }
    return <>{ showButton() }</>
    
}

export default Pay